<template>
    <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import * as echarts from 'echarts'

// 在 setup 作用域中定义 chartRef
const chartRef = ref()

//数据调用
const props = defineProps({
  xData: { type: Array, default: [] },
  yData: { type: Array, default: [] },
  title: { type: String, default: "数据趋势图" },
  legendName: { type: String, default: "内容数量" }
})

let myChart = null;
const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}
const initChart = () => {

  if (!chartRef.value) return;

  // 如果已有实例则先销毁
  if (myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartRef.value)

  var option = {
    title: {
      text: props.title
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        label: {
          backgroundColor: '#646cff'
        }
      }
    },
    legend: {
      data: [props.legendName]
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.xData
      // data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
    },
    yAxis: {
      type: 'value'
    },
    series: [
      {
        name: props.legendName,
        //   data: [820, 932, 901, 934, 1290, 1330, 1320],
        data: props.yData,
        type: 'line',
        smooth: true,
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: '#646cff'
              },
              {
                offset: 1,
                color: '#858bfd'
              }
            ],
            global: false
          }
        }
      }
    ]
  };
  option && myChart.setOption(option);
}

watch(() => props.xData, () => {
  initChart();
})

onMounted(() => {
  initChart();
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', resizeChart)
  myChart.dispose()
})
</script>